package com.sdx.console.spread.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.finOrderChannel.entity.FinOrderChannel;
import com.sdx.console.finOrderChannel.service.FinOrderChannelService;
import com.sdx.console.spread.entity.Channel;
import com.sdx.console.spread.service.ChannelService;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.service.ChannelSetService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ChannelSetController
 * @Description
 * @Author kangbin
 * @Date 2020/3/24 15:19
 */
@Controller
@RequestMapping("/spread/channelSet")
public class ChannelController extends AuthorizedBaesController {

    private static final String MODEL = "/spread/channelSet";

    @Resource
    private ChannelService channelService;


    @Resource
    private ChannelSetService channelSetService;

    @Resource
    private CorePlatformService corePlatformService;

    @Resource
    private CorePlatformService platformService;

    @Resource
    private OrgConsoleService orgConsoleService;

    @Resource
    private FinOrderChannelService finOrderChannelService;

    /**
     * 初始化页面需要的列表数据，
     *
     */
    private void setPageParam(ModelAndView view, HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        Integer accessType = corePlatformService.getAccessType(request);
        List<ChannelSet> channelList = channelSetService.selectAuthChannels(accessType, user.getOrgId(),user.getTenantId());
        view.addObject("channels",channelList);
        view.addObject("accessType",accessType);
        view.addObject("orgList",orgConsoleService.getOrgs());
    }

    /* 页面 */

    @GetMapping("/index.do")
    @Function("spread.channelSet.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }

    @PostMapping("/list.json")
    @Function("spread.channelSet.query")
    @ResponseBody
    public JsonResult<PageQuery> list(Channel condtion, HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        channelService.queryByCondition(page);
        return JsonResult.success(page);
    }


    @GetMapping("/add.do")
    @Function("spread.channelSet.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("spread.channelSet.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,String channelCode) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        setPageParam(view,request);
        CoreUser user = getLoginUser(request);
        Channel set = new Channel();
        set.setChannelCode(channelCode);
        set.setTenantId(user.getTenantId());
        Channel channel = channelService.getSqlManager().templateOne(set);  //queryById(channelCode);
        view.addObject("channel", channel);
        try {
            view.addObject("channelJson", JacksonUtils.toJsonString(channel,JacksonUtils.DF1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return view;
    }

    private JsonResult save(boolean isNew,Channel channel,HttpServletRequest request
    ) {
        JsonResult result = JsonResult.success();
        CoreUser user = getLoginUser(request);
        if (isNew) {
            channel.setTenantId(user.getTenantId());
            channel.setCreatedTime(new Date());
            channel.setChoicePrice(9999);
            boolean save = channelService.save(channel);
            if(save){
                initOrderChannel(user, channel.getChannelCode());
            }
        }else{
            channelService.update(channel);
        }
        return result;
    }
    @PostMapping("/add.json")
    @Function("spread.channelSet.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)Channel channel, HttpServletRequest request
    )
    {
        return save(true,channel,request );
    }

    @PostMapping("/update.json")
    @Function("spread.channelSet.edit")
    @ResponseBody
    public JsonResult update(@Validated(ValidateConfig.ADD.class)Channel channel, HttpServletRequest request
    )
    {
        return save(false,channel,request );
    }

    @PostMapping("/delete.json")
    @Function("spread.channelSet.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
        List<String> idList = new ArrayList<String>();
        Collections.addAll(idList,ids.split(","));
        channelService.batchDelChannelSet(idList);
        finOrderChannelService.batchDelFinOrderChannel(idList);
        return JsonResult.success();
    }

    public void initOrderChannel(CoreUser user,String channelCode){

        FinOrderChannel finOrder = new FinOrderChannel();
        finOrder.setTenantId(0);
        finOrder.setChannelCode("sdx");
        List<FinOrderChannel> finOrderChannels = finOrderChannelService.getSqlManager().template(finOrder);
        List<FinOrderChannel> list = new ArrayList<>();
        for (FinOrderChannel finOrderChannel : finOrderChannels) {
            FinOrderChannel channel = new FinOrderChannel();
            channel.setTenantId(user.getTenantId());
            channel.setChannelCode(channelCode);
            channel.setOrderType(finOrderChannel.getOrderType());
            channel.setOcStatus(1);
            channel.setPrice(finOrderChannel.getPrice());
            channel.setCreatedBy(user.getId().intValue());
            channel.setCreatedBy(user.getId().intValue());
            channel.setCreatedName(user.getName());
            channel.setCreatedTime(new Date());
            list.add(channel);
        }
        finOrderChannelService.getSqlManager().insertBatch(FinOrderChannel.class,list);
    }

}
